<template>
    <div>
        <div class="box-header">
            <b><span class="head-word">工具箱</span></b>
        </div>
        <div class="search-div">
            <Input v-model="searchData" placeholder="请输入工具名称" style="width: 60%" @keyup.enter.native="searchTool()"/>
            &nbsp;&nbsp;&nbsp;
            <Button ghost @click="searchTool()">搜索</Button>
            &nbsp;&nbsp;&nbsp;
            <Button ghost @click="addWebTool()">新增</Button>
        </div>
        <!--<img src="C:\Users\user\Desktop\icon.png" alt="" width="30px" height="30px">-->
        <div class="tool-bos-list">
            <Divider style="color: #ccc">系统应用</Divider>
            <Row>
                <template v-for="tool in showToolData">
                    <Col v-if="tool.type == 1" span="3">
                        <div class="one-tool">
                            <Button class="button" @click="toTool(tool.path)">
                                <img :src="require(`../assets/icon/tool-box/${tool.icon}`)" width="30px" height="30px">
                            </Button>
                            <div class="tool-word">{{tool.title}}</div>
                        </div>
                    </Col>
                </template>
            </Row>
            <br><br>
            <Divider style="color: #ccc">我的网络应用</Divider>
            <Row>
                <template v-for="tool in showToolData">
                    <Col v-if="tool.type == 2" span="3">
                        <div class="one-tool">
                            <Button class="button" @click="toWebTool(tool.path)">
                                <img :src="tool.icon" width="30px" height="30px">
                            </Button>
                            <div class="tool-word">{{tool.title}}</div>
                            <div style="text-align: center">
                                <span style="font-size: 12px; color: #ccc; cursor: pointer" @click="deleteWebTool(tool.id)">删除</span>
                            </div>
                        </div>
                    </Col>
                </template>
            </Row>
        </div>
        <Modal
                v-model="addModal"
                title="新增工具">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="工具名称" prop="title">
                    <Input v-model="formValidate.title" placeholder="请输入工具名称"></Input>
                </FormItem>
                <FormItem label="工具地址" prop="path">
                    <Input v-model="formValidate.path" placeholder="请输入浏览器地址"></Input>
                </FormItem>
                <FormItem label="工具图片">
                    <Input v-model="formValidate.icon" placeholder="请选择工具图片" style="width: 70%" readonly></Input>
                    <Button @click="selectPic()">选择图片</Button>
                </FormItem>
                <FormItem label="显示顺序">
                    <Input v-model="formValidate.tool_index" placeholder="请输入显示顺序"></Input>
                </FormItem>
                <FormItem label="备注">
                    <textarea v-model="formValidate.remark" placeholder="请输入文件备注" style="width: 100%"></textarea>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="addCancel">取消</Button>
                <Button type="primary" size="large" @click="addSave">确定</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
  import {getDB, userFolder} from '../js/dbUtil'
  const { dialog } = require('electron').remote
  export default {
    name: 'ToolBox',
    components: {},
    data () {
      return {
        searchData: '',
        showToolData: [],
        webToolData: [],
        localToolData: [
          {
            title: '行列互转',
            path: '/tool-row-to-col',
            icon: 'change-col-row.png',
            type: 1, // 1代表系统工具 2代表网络工具
            tool_index: 0,
            remark: ''
          },
          {
            title: '批量替换',
            path: '/batch-replace',
            icon: 'batch-replace.png',
            type: 1, // 1代表系统工具 2代表网络工具
            tool_index: 0,
            remark: ''
          },
          {
            title: '左右比较',
            path: '/let-right-compare',
            icon: 'compare.png',
            type: 1, // 1代表系统工具 2代表网络工具
            tool_index: 0,
            remark: ''
          },
          {
            title: '字符串瘦身',
            path: '/string-trim',
            icon: 'trim.png',
            type: 1, // 1代表系统工具 2代表网络工具
            tool_index: 0,
            remark: ''
          }
        ],
        allToolData: [],
        addModal: false,
        formValidate: {
          id: '',
          title: '',
          path: '',
          icon: '',
          type: 2,
          tool_index: 0,
          remark: ''
        },
        ruleValidate: {
          title: [
            {required: true, message: '工具名称不能为空', trigger: 'blur'}
          ],
          path: [
            {required: true, message: '工具地址不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    created () {
      console.info('初始化')
      this.loadWebToolData()
      this.allToolData = [...this.localToolData, ...this.webToolData]
      console.info('allToolData', this.allToolData.length)
      this.showToolData = this.allToolData
    },
    methods: {
      resetToolData () {
        this.allToolData = [...this.localToolData, ...this.webToolData]
        this.showToolData = this.allToolData
        console.info('resetToolData', this.showToolData.length)
      },
      toTool: function (path) {
        console.info('path', path)
        this.$router.push({path: path}).catch(err => {
          if (err.toString().indexOf('NavigationDuplicated') !== 0) {
            console.info('跳转页面异常', err)
          }
        })
      },
      toWebTool: function (path) {
        console.info('path', path)
        const { shell } = require('electron').remote
        shell.openExternal(path)
        // window.open(path, '子窗口', 'frame=true, toolbar=yes')
      },
      searchTool () {
        console.info('allToolData:', this.allToolData.length)
        console.info('搜索内容：', this.searchData)
        this.showToolData = this.allToolData
        if (this.searchData) {
          this.showToolData = this.showToolData.filter(item => item.title.indexOf(this.searchData) >= 0)
        }
      },
      addWebTool () {
        console.info('增加工具')
        this.addModal = true
      },
      addCancel () {
        console.info('新增')
      },
      addSave () {
        console.info('保存')
        let that = this
        this.$refs['formValidate'].validate(valid => {
          if (valid) {
            var UUID = require('uuid')
            let iconUUIDName = UUID.v1()
            console.info('icon_name', iconUUIDName)
            // 获取图片后缀
            let suffix = that.formValidate.icon.substring(that.formValidate.icon.lastIndexOf('.') + 1)
            let fullIconPath = userFolder() + '/tool/' + iconUUIDName + '.' + suffix
            let fs = require('fs')
            let sourceFile = that.formValidate.icon
            let destPath = fullIconPath
            let readStream = fs.createReadStream(sourceFile)
            let writeStream = fs.createWriteStream(destPath)
            readStream.pipe(writeStream)
            console.info('生成的图标路径为：', fullIconPath)

            // do some thing
            let db = getDB()

            db.all(`select title, path, icon, type, tool_index, remark from t_tool where path = $path`, {
              $path: that.formValidate.path
            }, function (err, row) {
              // console.info(sql)
              if (err) throw err
              else {
                console.log('查询结果数量', row.length)
                if (row.length === 0) {
                  db.run('insert into t_tool(title, path, icon, type, tool_index, remark) values ($title, $path, $icon, $type, $tool_index, $remark)', {
                    $title: that.formValidate.title,
                    $path: that.formValidate.path,
                    $icon: fullIconPath,
                    $type: that.formValidate.type,
                    $tool_index: that.formValidate.index,
                    $remark: that.formValidate.remark
                  }, function (err) {
                    if (err) {
                      that.$Message.error('新增失败')
                      throw err
                    } else {
                      that.$Message.success('新增成功')
                      that.formValidate.title = ''
                      that.formValidate.path = ''
                      that.formValidate.icon = ''
                      that.formValidate.type = ''
                      that.formValidate.tool_index = ''
                      that.formValidate.remark = ''
                      that.loadWebToolData()
                    }
                  })
                } else {
                  console.info('新增失败，与其他工具相同')
                  that.$Message.error('新增失败，与其他工具相同')
                }
              }
            })
            this.addModal = false // 关闭弹框
          }
        })
      },
      loadWebToolData () {
        let db = getDB()
        let that = this
        db.all(`select id, title, path, icon, type, tool_index, remark from t_tool`, function (err, row) {
          if (err) throw err
          else {
            console.log('查询结果数量', row.length)
            that.webToolData = row
            that.resetToolData()
          }
        })
      },
      selectPic () {
        console.info('选择图片')
        let that = this
        dialog.showOpenDialog({
          title: '请选择图标图片', // 对话框的标题
          properties: [], // 打开文件夹，默认打开文件，multiSelections可以多选
          filters: [
            {
              name: 'img',
              extensions: ['jpg', 'png'] // 只允许 jpg 和 png 格式的文件
            }
          ],
          buttonLabel: '请选择图片' // 自定义按钮文本显示内容
        }, function (data) {
          console.log('选择图片信息', data)
          if (data.length > 0) {
            that.formValidate.icon = data[0]
          }
        })
      },
      deleteWebTool (id) {
        console.info('删除id', id)
        this.$Modal.confirm({
          title: '删除',
          content: '<p>该操作将导致基础数据无法恢复，请谨慎操作！</p>',
          onOk: () => {
            let db = getDB()
            let that = this
            db.run('delete from t_tool where id = $id', {
              $id: id
            }, function (err) {
              if (err) {
                that.$Message.error('删除失败')
                throw err
              } else {
                that.$Message.success('删除成功')
                that.loadWebToolData()
                that.resetToolData()
              }
            })
          },
          onCancel: () => {

          }
        })
      }
    }
  }
</script>

<style scoped>
    .box-header {
        width: 90%;
        height: 60px;
        text-align: center;
        padding-top: 10px;
    }
    .search-div {
        width: 90%;
        height: 50%;
        text-align: center;
    }
    .head-word {
        font-size: 30px;
        margin-top: 10px;
        text-shadow: 3px 6px 10px #333;
        letter-spacing:6px;
    }
    .tool-bos-list {
        width: 90%;
        height: 400px;
        overflow: auto;
        background-color: #FFF;
        margin-top: 30px;
        margin-left: auto;
        margin-right: auto;
        padding-top: 20px;
    }
    .one-tool {
        margin-left: 20px;
        width: 60px;
    }
    .button {
        box-shadow: 3px 3px 3px #ccc;
    }
    .tool-word {
        text-align: center;
        margin-top: 6px;
        color: cadetblue;
    }
</style>
